from  Indicators import *

def strategys(row,file_name): #args 存放需要写入的策略
    ts_code=row['ts_code']
    name=row['name']
    area=row['area']
    industry=row['industry']
    list_date=row['list_date']
    df=get_data(ts_code)
    output_File = open(file_name,'a+') 
    if df.empty:
        return "%s df is []"%ts_code
    else:
        close=df["Close"][-1]
        zjjr=str(round(zjjr_I(df)[-1],2))
        zjxc=str(round(zjxc_I(df)[-1],2))
        cdsz=str(round(cdsz_I(df)[-1],2))
        dkcw=str(round(dkcw_I(df)[-1],2))
        output_File.write('{},{},{},{},{},{},{},{},{},{}\n'.format(ts_code,close,name,area,industry,list_date,zjxc,zjjr,dkcw,cdsz))
        output_File.flush()
        if isinstance(ts_code,int):
            return "%s complete"%str(ts_code).zfill(6)
        else:
            return "%s complete"%ts_code

def multi_thread_output(file_name,df):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    import concurrent.futures
    #在append之前先删除原数据表
    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(strategys,row,file_name) for index,row in df.iterrows()] #只要结果的最后一项，表示最近一天数据
        for f in concurrent.futures.as_completed(results):
            print(f.result()) 

if __name__=='__main__':
    path=os.getcwd()
    # df=pd.read_csv(path+'/f10_true.csv')
    # code_index_list=df['code'].to_list()
    df=pd.read_csv(path+'/main_stock.csv')
    fn="./Result/strategys%s.csv"%str(time.strftime("%Y_%m_%d"))
    if os.path.exists(fn):
        os.remove(fn)
    output_File = open(fn,'a+')
    #写入表头
    output_File.write('{},{},{},{},{},{},{},{},{},{}\n'.format('code','close','name','area','industry','list_date','zjxc','zjjr','dkcw','cdsz'))
    output_File.flush() 
    multi_thread_output(fn,df)
    send_to_email(fn,path+fn)